package ink.metoo.gude.module.security.service.impl

import ink.metoo.gude.handler.ApiException
import ink.metoo.gude.model.ApiStatus
import ink.metoo.gude.module.security.domain.ddl.User
import ink.metoo.gude.module.security.domain.dto.UpdateUserSettingDTO
import ink.metoo.gude.module.security.repository.UserRepository
import ink.metoo.gude.module.security.service.UserService
import ink.metoo.gude.module.file.model.FileCatalog
import ink.metoo.gude.module.file.service.FileService
import ink.metoo.gude.util.RegexUtils
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile

@Service
class UserServiceImpl(
    private val userRepository: UserRepository,
    private val fileService: FileService
) : UserService {

    override fun fuzzySearch(n: String, size: Int) = userRepository.findAllByAccountLike(n, size)

    @Transactional
    override fun updateSetting(
        user: User,
        updateSetting: UpdateUserSettingDTO
    ) {
        user.nickname = updateSetting.nickname
        user.introduction = updateSetting.introduction
        user.gender = updateSetting.gender
        userRepository.save(user)
    }

    @Transactional
    override fun uploadAvatar(
        user: User,
        file: MultipartFile
    ): String {
        val fileType = file.contentType?.split("/")?.get(1)
        if (fileType == null || !RegexUtils.IMG_REGEX.matches(fileType)) {
            throw ApiException(ApiStatus.F_4001)
        }

        val key = FileCatalog.USER_AVATAR.fill(
            "uid" to user.id.toString(),
            "filename" to "${System.currentTimeMillis()}.$fileType",
        )
        val url = fileService.upload(key, file)
        user.avatar = url
        userRepository.save(user)
        return url
    }


}
